import axios from 'axios'
import type { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios'

// import { notification } from 'ant-design-vue'
// import { UseUIStore } from '@/@base/store/UI'
// import { GetToken } from './auth' // 假设这个文件存在或将来会创建

// 定义请求选项接口
export interface HttpOptions {
    url: string;
    type: 'GET' | 'POST' | 'PUT' | 'DELETE';
    params?: Record<string, any>;
    data?: any;
    config?: AxiosRequestConfig;
}

// 创建axios实例
const server: AxiosInstance = axios.create({
    // baseURL: import.meta.env.VITE_APP_API_HOST,
    timeout: 90 * 1000
})

server.defaults.headers.post['Content-Type'] = 'application/json';

// 请求拦截器
server.interceptors.request.use((config: InternalAxiosRequestConfig<any>): InternalAxiosRequestConfig<any> => {
    // const token: string | null = GetToken();
    // if (token) {
    //     config.headers = config.headers || {};
    //     config.headers.Authorization = 'Bearer ' + token;
    // }
    return config;
}, (error: AxiosError): Promise<AxiosError> => {
    return Promise.reject(error);
})

// 响应拦截器
server.interceptors.response.use((response: AxiosResponse): any => {
    return response.data;
}, (error: AxiosError): Promise<AxiosError> => {
    // if (!error.response) {
    //     return Promise.reject(error);
    // };

    // if (error.response.status == 403) {
    //     notification.error({ message: 'Service Error 403', description: '参数错误，请检查参数信息', });
    // } else if (error.response.status == 400) {
    //     notification.error({ message: 'Service Error 400', description: '参数错误，请检查参数信息', });
    // } else if (error.response.status == 404) {
    //     notification.error({ message: 'Service Error 404', description: '未找到接口，请检查链接地址', });
    // } else if (error.response.status == 500) {
    //     notification.error({ message: 'Service Error 500', description: '服务器出现错误', });
    // } else if (error.response.status == 502) {
    //     notification.error({ message: 'Service Error 502', description: '服务器响应出现错误', });
    // } else {
    //     notification.error({ message: 'Service Error' + error.response.status, description: '链接异常，请检查错误信息', });
    // }
    return Promise.reject(error);
})

// HTTP请求函数
export const http = function (options: HttpOptions): Promise<any> {
    let _url: string = options.url;
    let _params: Record<string, any> = JSON.parse(JSON.stringify(options.data || {}));

    _url = _url.replace(/\/\:\w+\\/g, function (i: string): string {
        const _src: string = i.replace('/:', '').replace('/', '');
        if (_params.hasOwnProperty(_src)) {
            const _value: string = _params[_src];
            delete _params[_src];
            return _value;
        }
        return i; // 如果找不到对应的参数，保留原字符串
    });



    return server({
        method: options.type,
        url: _url,
        params: _params,
        data: options.data,
    });
};

export default http;
